const logger = require("../lib/logger");
const { spawn } = require("child_process");
const { resolve } = require("path");

const status = {};
let gpioProcess = spawn(`sudo`, [
  process.execPath,
  resolve(__dirname, "./gpio.js"),
], {
  stdio: ['pipe', 'pipe', 'pipe', 'ipc'] // 添加IPC支持
});

// GPIO进程重启函数
function restartGpioProcess() {
  try {
    if (gpioProcess && !gpioProcess.killed) {
      gpioProcess.kill('SIGTERM');
    }
    setTimeout(() => {
      gpioProcess = spawn(`sudo`, [
        process.execPath,
        resolve(__dirname, "./gpio.js"),
      ], {
        stdio: ['pipe', 'pipe', 'pipe', 'ipc'] // 添加IPC支持
      });
      setupGpioProcessHandlers();
      logger.info('[GPIO Server] 进程已重启');
    }, 1000);
  } catch (error) {
    logger.error('[GPIO Server] 重启失败:', error.message);
  }
}

// 设置GPIO进程事件处理器
function setupGpioProcessHandlers() {
  gpioProcess.stderr.on("data", (data) => {
    const errorMsg = data.toString();
    if (errorMsg.includes('ERR_INVALID_ARG_TYPE')) {
      logger.warn(`[GPIO Server] 参数类型错误，尝试重启 GPIO 进程`);
      restartGpioProcess();
    } else {
      logger.error(`[GPIO Server Error] ${errorMsg}`);
    }
  });

  // 添加对子进程日志消息的处理
  gpioProcess.on('message', (message) => {
    if (message && message.type === 'log') {
      // 根据日志级别调用相应的日志方法
      const logMessage = `[GPIO] ${message.message}`;
      switch (message.level) {
        case 'error':
          logger.error(logMessage);
          break;
        case 'warn':
          logger.warn(logMessage);
          break;
        case 'info':
          logger.info(logMessage);
          break;
        case 'debug':
          logger.debug(logMessage);
          break;
        default:
          logger.info(logMessage);
      }
    }
  });

  gpioProcess.stdout.on("data", (data) => {
    // 将stdout数据转发到日志
    const output = data.toString().trim();
    if (output) {
      logger.debug(`[GPIO stdout] ${output}`);
    }
  });

  gpioProcess.on('exit', (code, signal) => {
    logger.warn(`[GPIO Server] 进程退出，退出码: ${code}, 信号: ${signal}`);
    if (code !== 0 && code !== null) {
      logger.info('[GPIO Server] 尝试重启进程...');
      setTimeout(() => restartGpioProcess(), 2000);
    }
  });

  gpioProcess.on('error', (error) => {
    logger.error('[GPIO Server] 进程错误:', error.message);
  });
}

// 初始化事件处理器
setupGpioProcessHandlers();

exports.listen = function (pin, callback) {
  gpioProcess.stdin.write(`listen ${pin}\n`);
  gpioProcess.stdout.on("data", (data) => {
    //   logger.info(`[GPIO Server Out]`, data);
    if (data.toString().includes("gpio-change")) {
      const [, json] = data.toString().split("|");
      const { pin, value } = JSON.parse(json);
      if (pin === pin) {
        callback(value);
      }
    }
  });
};

exports.changePwmPin = function (pin, v) {
  if (gpioProcess && !gpioProcess.killed) {
    logger.info(`[GPIO Server] Sending command: pwm ${pin} ${v}`);
    gpioProcess.stdin.write(`pwm ${pin} ${v}\n`);
  } else {
    logger.warn('[GPIO Server] 进程不可用，跳过PWM控制');
  }
};
exports.changeSwitchPin = function (pin, v) {
  if (gpioProcess && !gpioProcess.killed) {
    gpioProcess.stdin.write(`sw ${pin} ${v}\n`);
  } else {
    logger.warn('[GPIO Server] 进程不可用，跳过开关控制');
  }
};
exports.channelStatus = status;

exports.closeChannel = function () {
  if (gpioProcess && !gpioProcess.killed) {
    gpioProcess.stdin.write(`close\n`);
  }
};

process.on("exit", () => {
  if (gpioProcess && !gpioProcess.killed) {
    gpioProcess.stdin.write(`exit\n`);
    gpioProcess.kill('SIGTERM');
  }
});